<template>
  <div class="file-reader-container">
    <!-- 页面头部 -->
    <!-- <PageHeader 
      title="文件阅读器"
      :has-back="true"
      @back="goBack"
    >
      <template #actions>
        <el-button-group>
          <el-tooltip content="切换预览组件" placement="top">
            <el-button type="primary" @click="togglePreviewComponent">
              <el-icon><Monitor /></el-icon>
              {{ useFilePreview ? 'FilePreview' : 'DocumentViewer' }}
            </el-button>
          </el-tooltip>
          <el-tooltip content="返回文件库" placement="top">
            <el-button type="primary" @click="goToFileLibrary">
              <el-icon><Folder /></el-icon>
              文件库
            </el-button>
          </el-tooltip>
        </el-button-group>
      </template>
    </PageHeader> -->
    
    <div class="main-content">
      <!-- 侧边栏 -->
      <div class="sidebar" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
        <!-- 文件上传区域 -->
        <div class="upload-area">
          <el-upload
            class="file-uploader"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            :multiple="true"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
          </el-upload>
        </div>
        
        <!-- 历史记录 -->
        <div class="history-section">
          <div class="section-header">
            <h3>最近文件</h3>
            <el-button 
              type="text" 
              size="small" 
              @click="clearHistory"
              v-if="fileHistory.history.length > 0"
            >
              清空
            </el-button>
          </div>
          
          <div class="history-list" v-if="fileHistory.history.length > 0">
            <div 
              v-for="file in fileHistory.recentFiles" 
              :key="file.id"
              class="history-item"
              @click="loadFileFromHistory(file.id)"
            >
              <el-icon class="file-icon">
                <DocumentCopy v-if="file.type === 'document'" />
                <Memo v-else-if="file.type === 'markdown'" />
                <Picture v-else-if="file.type === 'image'" />
                <VideoPlay v-else-if="file.type === 'video'" />
                <Document v-else />
              </el-icon>
              <div class="file-info">
                <div class="file-name">{{ file.name }}</div>
                <div class="file-time">{{ formatTime(file.timestamp) }}</div>
              </div>
            </div>
          </div>
          
          <el-empty 
            v-else 
            description="暂无历史记录" 
            :image-size="100"
          />
        </div>
      </div>
      
      <!-- 侧边栏切换按钮 -->
      <div class="sidebar-toggle" @click="toggleSidebar">
        <el-icon :size="18">
          <ArrowRight v-if="sidebarCollapsed" />
          <ArrowLeft v-else />
        </el-icon>
      </div>
      
      <!-- 主内容区域 -->
      <div class="content-area">
        <!-- 无文件提示 -->
        <div v-if="!currentFile" class="empty-state">
          <el-empty description="请上传或选择文件进行预览">
            <el-button type="primary" @click="triggerFileUpload">上传文件</el-button>
          </el-empty>
        </div>
        
        <!-- 文件预览区域 -->
        <div v-else class="preview-container">
          <!-- 使用FilePreview组件 -->
          <FilePreview 
            v-if="useFilePreview && currentPreviewFile"
            :fileUrl="currentPreviewFile.fileUrl"
            :fileName="currentPreviewFile.fileName"
            :fileType="currentPreviewFile.fileType"
            @back="goBack"
          />
          
          <!-- 使用DocumentViewer组件 -->
          <DocumentViewer 
            v-else
            :document-url="currentFile.url || URL.createObjectURL(currentFile.raw)"
            :document-name="currentFile.name"
            :document-type="getFileType(currentFile.name)"
          />
        </div>
      </div>
    </div>
    
    <!-- 文件浏览器对话框 -->
    <el-dialog
      v-model="fileExplorerVisible"
      title="文件库"
      width="80%"
      destroy-on-close
    >
      <FileExplorer
        :use-cos-service="true"
        :cos-config="cosServiceConfig"
        :can-upload="false"
        :can-create-folder="false"
        :can-delete="false"
        @file-read="openFileInReader"
      />
    </el-dialog>
 
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { 
  Upload, 
  Document, 
  Memo, 
  DocumentCopy, 
  ArrowRight, 
  ArrowLeft,
  Picture,
  VideoPlay,
  UploadFilled
} from '@element-plus/icons-vue';
import FilePreview from '../components/FilePreview/index.vue';
import DocumentViewer from '../components/common/DocumentViewer.vue';
import { useFileHistoryStore, useFilePreviewStore } from '../store';
import FileExplorer from '../components/FileExplorer/index.vue';
import { initCosFileService, getFileType as getFileTypeFromService } from '../utils/dataService';
import cosConfig from '../utils/cosConfig';

// 文件历史记录Store
const fileHistory = useFileHistoryStore();
// 文件预览Store
const filePreviewStore = useFilePreviewStore();

// 路由相关
const route = useRoute();
const router = useRouter();
const fileId = ref(route.query.id || null);
const shareData = ref(route.query.share || null);
const fileUrl = ref(route.query.url || null);
const fileName = ref(route.query.name || null);
const fileType = ref(route.query.type || null);

// 状态管理
const fileList = ref([]);
const currentFileIndex = ref(-1);
const sidebarCollapsed = ref(false);
const fileExplorerVisible = ref(false);

// 当前文件
const currentFile = computed(() => {
  if (currentFileIndex.value >= 0 && currentFileIndex.value < fileList.value.length) {
    return fileList.value[currentFileIndex.value];
  }
  return null;
});

// COS配置
const cosServiceConfig = { ...cosConfig };

// 使用FilePreview组件
const useFilePreview = ref(true);
const currentPreviewFile = computed(() => {
  if (!currentFile.value) {
    // 如果有URL参数但没有当前文件，直接使用URL参数
    if (fileUrl.value) {
      return {
        fileUrl: fileUrl.value,
        fileName: fileName.value || '未命名文件',
        fileType: fileType.value || getFileType(fileName.value || '')
      };
    }
    return null;
  }
  
  const fileType = currentFile.value.type || getFileType(currentFile.value.name);
  
  return {
    fileUrl: currentFile.value.url || (currentFile.value.raw ? URL.createObjectURL(currentFile.value.raw) : ''),
    fileName: currentFile.value.name,
    fileType: fileType
  };
});

// 切换预览组件
const togglePreviewComponent = () => {
  useFilePreview.value = !useFilePreview.value;
  ElMessage.info(`已切换到${useFilePreview.value ? 'FilePreview' : 'DocumentViewer'}组件`);
};

// 处理文件上传
const handleFileChange = (file) => {
  if (fileList.value.some(f => f.name === file.name && f.size === file.size)) {
    return;
  }
  
  fileList.value.push(file);
  currentFileIndex.value = fileList.value.length - 1;
  addFileToHistory(file);
};

// 添加文件到历史记录
const addFileToHistory = (file) => {
  const fileUrl = URL.createObjectURL(file.raw);
  
  fileHistory.addToHistory({
    name: file.name,
    url: fileUrl,
    type: getFileType(file.name),
    source: 'local'
  });
};

// 从历史记录加载文件
const loadFileFromHistory = (id) => {
  const historyFile = fileHistory.getFileById(id);
  
  if (!historyFile) {
    ElMessage.error('文件不存在或已被删除');
    return;
  }
  
  fileHistory.loadFileById(id);
  
  if (historyFile.source === 'local') {
    loadLocalFileFromHistory(historyFile);
  } else if (historyFile.source === 'remote') {
    loadFileFromUrl(historyFile.url, historyFile.name, historyFile.type);
  }
};

// 从历史记录加载本地文件
const loadLocalFileFromHistory = async (historyFile) => {
  try {
    const response = await fetch(historyFile.url);
    if (!response.ok) {
      throw new Error(`无法获取文件内容: ${response.status}`);
    }
    
    const blob = await response.blob();
    const fileType = historyFile.type || getFileType(historyFile.name);
    
    const file = new File([blob], historyFile.name, { type: blob.type || 'application/octet-stream' });
    
    const uploadFile = {
      name: file.name,
      size: file.size,
      raw: file,
      url: historyFile.url,
      type: fileType
    };
    
    fileList.value = [uploadFile];
    currentFileIndex.value = 0;
    
    filePreviewStore.setFile({
      name: file.name,
      url: historyFile.url,
      type: fileType
    });
    
    ElMessage.success(`已加载文件: ${historyFile.name}`);
  } catch (err) {
    console.error('加载历史文件失败:', err);
    ElMessage.error('文件加载失败，可能已过期');
    fileHistory.removeFile(historyFile.id);
  }
};

// 从URL加载文件
const loadFileFromUrl = (url, name, type) => {
  if (!url || !name) {
    ElMessage.error('文件信息不完整');
    return;
  }
  
  try {
    fileHistory.addToHistory({
      name: name,
      url: url,
      type: type || getFileType(name),
      source: 'remote'
    });
    
    const extension = name.split('.').pop().toLowerCase();
    if (['pdf', 'html', 'htm', 'md', 'markdown', 'txt'].includes(extension)) {
      const fileType = type || getFileType(name);
      
      const uploadFile = {
        name: name,
        size: '-',
        url: url,
        type: fileType
      };
      
      fileList.value = [uploadFile];
      currentFileIndex.value = 0;
      
      filePreviewStore.setFile({
        name: name,
        url: url,
        type: fileType
      });
      
      return;
    }
    
    fetch(url, { 
      mode: 'no-cors'
    })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.blob();
      })
      .then(blob => {
        const file = new File([blob], name, { type: blob.type });
        const fileType = type || getFileType(name);
        
        const uploadFile = {
          name: file.name,
          size: file.size,
          raw: file,
          url: url,
          type: fileType
        };
        
        fileList.value = [uploadFile];
        currentFileIndex.value = 0;
        
        filePreviewStore.setFile({
          name: file.name,
          url: url,
          type: fileType
        });
      })
      .catch(err => {
        console.error('加载文件失败:', err);
        ElMessage.error('加载文件失败，请重试');
        
        console.log('尝试直接使用URL加载文件');
        const fileType = type || getFileType(name);
        
        const uploadFile = {
          name: name,
          size: '-',
          url: url,
          type: fileType
        };
        
        fileList.value = [uploadFile];
        currentFileIndex.value = 0;
        
        filePreviewStore.setFile({
          name: name,
          url: url,
          type: fileType
        });
      });
  } catch (error) {
    console.error('处理文件数据失败:', error);
    ElMessage.error('处理文件数据失败');
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const now = new Date();
  
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }
  
  const daysDiff = Math.floor((now - date) / (1000 * 60 * 60 * 24));
  if (daysDiff < 7) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return weekdays[date.getDay()];
  }
  
  return date.toLocaleDateString();
};

// 获取文件类型
const getFileType = (fileName) => {
  return getFileTypeFromService(fileName);
};

// 清空历史记录
const clearHistory = () => {
  fileHistory.$reset();
  ElMessage.success('历史记录已清空');
};

// 返回上一页
const goBack = () => {
  // 如果是从历史记录中点击进入的，返回上一页
  if (window.history.length > 1 && document.referrer) {
    router.go(-1);
  } else {
    // 否则直接返回首页
    router.push('/');
  }
};

// 打开文件库
const goToFileLibrary = () => {
  fileExplorerVisible.value = true;
};

// 触发文件上传
const triggerFileUpload = () => {
  const uploadInput = document.querySelector('.file-uploader input[type="file"]');
  if (uploadInput) {
    uploadInput.click();
  }
};

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value;
};

// 从文件浏览器打开文件
const openFileInReader = (file) => {
  loadFileFromUrl(file.url, file.name, file.type);
  fileExplorerVisible.value = false;
};

// 从URL参数加载文件
const loadFromUrlParams = () => {
  if (fileUrl.value) {
    const url = decodeURIComponent(fileUrl.value);
    const name = fileName.value ? decodeURIComponent(fileName.value) : '未命名文件';
    const type = fileType.value ? decodeURIComponent(fileType.value) : getFileType(name);
    
    loadFileFromUrl(url, name, type);
    return true;
  }
  return false;
};

// 组件挂载
onMounted(() => {
  initCosFileService(cosServiceConfig);
  
  // 优先从URL参数加载
  if (loadFromUrlParams()) {
    return;
  }
  
  if (fileId.value) {
    loadFileFromHistory(fileId.value);
  } else if (shareData.value) {
    try {
      const data = JSON.parse(atob(shareData.value));
      if (data.url && data.name) {
        loadFileFromUrl(data.url, data.name, data.type);
      }
    } catch (error) {
      console.error('解析分享数据失败:', error);
      ElMessage.error('无效的分享链接');
    }
  } else {
    const storeFile = filePreviewStore.currentFile;
    if (storeFile) {
      loadFileFromUrl(storeFile.url, storeFile.name, storeFile.type);
    } else {
      const storedFile = localStorage.getItem('selectedFile');
      if (storedFile) {
        try {
          const fileData = JSON.parse(storedFile);
          loadFileFromUrl(fileData.url, fileData.name, fileData.type);
        } catch (error) {
          console.error('解析本地存储文件数据失败:', error);
        }
      }
    }
  }
});
</script>

<style scoped>
.file-reader-container {
  height: calc(100vh - 66px);
  width: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f9fafb;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
  position: relative;
}

/* 侧边栏样式 */
.sidebar {
  width: 280px;
  background-color: white;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  height: 100%;
}

.sidebar-collapsed {
  width: 0;
  border-right: none;
}

/* 侧边栏切换按钮 */
.sidebar-toggle {
  position: absolute;
  top: 200px;
  left: 280px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 150;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.sidebar-toggle:hover {
  background-color: #f3f4f6;
  transform: scale(1.05);
}

.sidebar-toggle:active {
  transform: scale(0.95);
}

/* 侧边栏收缩后切换按钮位置调整 */
.sidebar-collapsed + .sidebar-toggle {
  left: 0;
}

/* 上传区域样式 */
.upload-area {
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
}

/* 历史记录区域样式 */
.history-section {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.section-header h3 {
  font-size: 1rem;
  font-weight: 600;
  color: #4b5563;
  margin: 0;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 0.75rem;
  border-radius: 0.5rem;
  background-color: #f9fafb;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.history-item:hover {
  background-color: #f3f4f6;
}

.file-icon {
  font-size: 1.25rem;
  margin-right: 0.75rem;
  color: #6b7280;
}

.file-info {
  flex: 1;
  overflow: hidden;
}

.file-name {
  font-size: 0.875rem;
  font-weight: 500;
  color: #1f2937;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-time {
  font-size: 0.75rem;
  color: #6b7280;
  margin-top: 0.25rem;
}

/* 主内容区域样式 */
.content-area {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

.preview-container {
  flex: 1;
  overflow: hidden;
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    z-index: 100;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    transform: translateX(0);
  }
  
  .sidebar-collapsed {
    transform: translateX(-100%);
    width: 280px;
  }
  
  .sidebar-toggle {
    top: 15px;
    left: 280px;
    background-color: white;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  }
  
  .sidebar-collapsed + .sidebar-toggle {
    left: 0;
  }
}
</style> 